/**
 * 与某个角色关联的用户列表面板，提供添加和删除关联功能
 * @author linzongxue
 * @create_date 2012-1-7
 */
define(function(){
	var RoleUserPanel = Ext.extend(Ext.grid.GridPanel, {
		role: null, //当前角色信息
		roleChanged: false,
		title: '关联用户',
		border: false,
		stripeRows: true,
	    enableHdMenu: false,
		initComponent: function(){
			this.tbar = au.permit([
				{text: '添加', permitId:'sys.role.addUser', handler: this.addUsers,scope: this, iconCls: 'icon-add', tooltip:'添加关联用户'},
				{text: '删除', permitId:'sys.role.removeUser',handler: this.removeUsers,scope: this, iconCls: 'icon-delete', tooltip:'删除关联用户'},
				'-',
				{text: '刷新', handler: function(){this.refresh(true);}, scope: this, iconCls: 'icon-refresh'},
				'->',
				{xtype: 'label', name:'curRole'}, //显示角色名称
				'-'
            ]);
			this.store = new Ext.data.JsonStore({
				fields: ['loginName', 'name', 'departName'],
				url: 'sys/role/getUsersOfRole.do'
			});
			this.columns = [
				new Ext.grid.RowNumberer(),
			    this.sm = new Ext.grid.CheckboxSelectionModel(),
				{header: '账号', width: 120, dataIndex: 'loginName'},
				{header: '姓名', width: 150, dataIndex: 'name'},
				{header: '所属机构', width: 150, dataIndex: 'departName'}
			];
			RoleUserPanel.superclass.initComponent.call(this);
			this.on({
				activate: function(){
					this.refresh();
				}
			});
		},
		/**
		 * @param force 是否强制刷新，默认不强制刷新
		 */
		refresh: function(force){
			var curRoleLabel =  this.getTopToolbar().find('name', 'curRole')[0];
			if (!this.role){
				this.store.removeAll();
				curRoleLabel.setText('未选中角色');
				return;
			}
			if (force || this.roleChanged){
				this.store.load({
					params: {roleId: this.role.id}
				});
			}
			curRoleLabel.setText('当前角色：' + this.role.name);
			this.roleChanged = false;
		},
		setRole: function(role){
			this.role = role;
			this.roleChanged = true;
		},
		addUsers: function(){
			if (!this.role){
				cu.hint('未选中角色');
				return;
			}
			use('sys.role.SelectUserWindow', function(Win){
				new Win({
					roleId: this.role.id,
					selectedUserIds: lu.pluck(this.store.getRange(), 'id'),
					callback: function(data){
						cu.hint('成功添加' + data + '个用户关联');
						this.refresh(true);
					},
					cbScope: this
				}).show();
			}, this);
		},
		removeUsers: function(){
			var records = this.getSelectionModel().getSelections();
			if (records.length == 0){
				cu.hint('请选择要删除关联的用户');
				return;
			}
			var msg = '确定要删除选中的' + records.length + '个用户关联吗？';
			cu.confirm(msg, function(){
				cu.post({
					url: 'sys/role/removeUsersFromRole.do',
					params: {roleId: this.role.id,userIds: lu.pluck(records, 'id')},
					success: function(){
						this.getStore().remove(records);
					},
					scope: this
				});
			}, this);
		}
	});
	return RoleUserPanel;
});